package com.nlp.server.controller;

import com.nlp.common.core.exception.ServiceException;
import com.nlp.common.core.web.controller.BaseController;
import com.nlp.common.core.web.pojo.AjaxResult;
import com.nlp.server.factory.ChatQueryFactory;
import com.nlp.server.pojo.dto.ChatDTO;
import com.nlp.server.service.ChatService;
import com.nlp.server.strategy.ChatQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.ExecutorService;

/**
 * 对话控制层
 * @author shiliuyinzhen
 */
@RestController
@RequestMapping("/chat")
@Api(tags = "对话相关接口")
public class ChatController extends BaseController {

    @Autowired
    private ChatService chatService;

    @Autowired
    private ExecutorService chatExecutorService;

    @Autowired
    private ChatQueryFactory chatQueryFactory;

    /**
     * 开启新会话
     * @return
     */
    @PostMapping("/create")
    @ApiOperation("开启新会话")
    public AjaxResult createChat(){
        return chatService.createChat();
    }

    /**
     * 查询问题
     * @param chatDTO
     * @return
     */
    @ApiOperation("查询问题")
    @PostMapping(value = "/query",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter query(@RequestBody ChatDTO chatDTO) {
        //是否断开SSE连接
//        SseEmitter sseEmitter = SseEmitterUtils.addSseEmitter(SecurityUtils.getUserId());
        SseEmitter sseEmitter = new SseEmitter(600000L);//超时时间10min
        //将任务提交给线程池
        chatExecutorService.execute(() -> {
            ChatQuery chatQuery = chatQueryFactory.getChatQuery(chatDTO.getType());
            if (chatQuery == null) {
                throw new ServiceException("未找到查询策略");
            }
            chatQuery.query(chatDTO,sseEmitter);
        });
        return sseEmitter;
    }
}
